package com.wss.common.context.util;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;

public class HttpRequestProxyUtil {

    private static Logger logger = Logger.getLogger(HttpRequestProxyUtil.class);

    public HttpRequestProxyUtil() {
    }

    public static String executeHttpPost(String url, List<Map<String, String>> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            UrlEncodedFormEntity urlEncodedFormEntity = getUrlEncodedFormEntity(params);
            if(urlEncodedFormEntity != null) {
                httpPost.setEntity(urlEncodedFormEntity);
            }

            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpPost.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

        return result;
    }

    public static String executeJsonParamHttpPost(String url, String textMsg) throws Exception {

        logger.info("调用接口服务URL："+url);
        logger.info("参数textMsg:"+textMsg);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(textMsg, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpPost.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

        logger.info("调用接口反馈:"+result);
        return result;
    }

    public static String executeHttpGet(String url, List<Map<String, String>> params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            UrlEncodedFormEntity urlEncodedFormEntity = getUrlEncodedFormEntity(params);
            if(urlEncodedFormEntity != null) {
                url = url + "?" + EntityUtils.toString(urlEncodedFormEntity);
            }

            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpGet);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpGet.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }

        return result;
    }

    private static UrlEncodedFormEntity getUrlEncodedFormEntity(List<Map<String, String>> params) {
        ArrayList formparams = new ArrayList();
        if(params != null && params.size() > 0) {
            for(int entity = 0; entity < params.size(); ++entity) {
                Iterator var4 = ((Map)params.get(entity)).keySet().iterator();

                while(var4.hasNext()) {
                    String key = (String)var4.next();
                    formparams.add(new BasicNameValuePair(key, (String)((Map)params.get(entity)).get(key)));
                }
            }
        }
        if(formparams.size()>0) {
            UrlEncodedFormEntity var6 = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            return var6;
        }
        return null;
    }

    public static void getDownloadFile(String url, List<Map<String, String>> params, String destFileName, boolean useConfigdbKey) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httppost = new HttpGet(url);
        CloseableHttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        File file = new File(destFileName);

        try {
            FileOutputStream fout = new FileOutputStream(file);
            boolean l = true;
            byte[] tmp = new byte[1024];

            while(true) {
                int l1;
                if((l1 = in.read(tmp)) == -1) {
                    fout.flush();
                    fout.close();
                    break;
                }

                fout.write(tmp, 0, l1);
            }
        } finally {
            in.close();
        }

        httpclient.close();
    }

    public static String uploadFile(String url, List<Map<String, String>> params, Map<String, String> files) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        FileBody fileBody = null;
        String result = null;
        if(files != null) {
            Iterator response = files.keySet().iterator();

            while(response.hasNext()) {
                String entitys = (String)response.next();
                fileBody = new FileBody(new File((String)files.get(entitys)));
                builder.addPart(entitys, fileBody);
            }
        }

        for(int var20 = 0; params != null && var20 < params.size(); ++var20) {
            Map var22 = (Map)params.get(var20);
            Iterator var10 = var22.keySet().iterator();

            while(var10.hasNext()) {
                String key = (String)var10.next();
                builder.addTextBody(key, (String)var22.get(key));
            }
        }

        try {
            post.setEntity(builder.build());
            CloseableHttpResponse var21 = httpclient.execute(post);
            if(200 == var21.getStatusLine().getStatusCode()) {
                try {
                    HttpEntity var23 = var21.getEntity();
                    if(var23 != null) {
                        result = EntityUtils.toString(var23);
                    }

                    post.abort();
                } finally {
                    var21.close();
                }
            }
        } finally {
            httpclient.close();
        }

        return result;
    }

    public static void main(String[] args) throws Exception {
        ArrayList params = new ArrayList();
        HashMap map = new HashMap();
        map.put("name", "张三");
        params.add(map);
        System.out.println(executeHttpGet("http://localhost:8080/emcon/test.do", params));
    }
}
